<template>
  <div>
    <div class="downbtn" @click="visible = true">
      <p class="downicon"><i class="iconsys icondown" style="font-size:20px;"></i></p>
      <p class="downp">下载中心</p>
    </div>
    <Drawer v-model="visible"
      transfer
      title="下载管理中心"
      :mask-closable="true"
      @on-close="handleClose"
      width="1000">
      <div class="search-box">
        <Row type="flex">
          <Row type="flex"
            justify="start">
            <Col class="search-item"  v-show="!taskMd5">
              <span class="search-label">文件状态:</span>
              <Select v-model="searchObj.downLoadStatus" @on-change="search">
                <Option :value="item.value" :key="index" v-for="(item, index) in statusList">{{item.label}}</Option>
              </Select>
            </Col>
            <Col class="search-item"  v-show="!taskMd5">
              <span class="search-label" style="float:left;padding-top: 7px;">门店:</span>
              <div style="float:left;">
              <vueTreeselectChoice
                :multiple="true"
                ref="vueTreeselectChoice"
                value-consists-of="LEAF_PRIORITY"
                @input="handleShop"
                v-model="shopValue"
                :permissionCode="perms"
              ></vueTreeselectChoice>
              </div>
            </Col>
            <Col class="search-item"  v-show="!taskMd5">
              <span class="search-label">任务模块:</span>
              <Select v-model="searchObj.taskModule" @on-change="search">
                <Option :value="-1">全部</Option>
                <Option :value="item.taskModuleCode" :key="index" v-for="(item, index) in taskModuleList">{{item.taskMoudleName}}</Option>
              </Select>
            </Col>
            <Col class="search-item" v-show="!taskMd5">
              <Button class="search-btn"
                type="primary"
                @click="getData">查询</Button>
            </Col>
            <Col class="search-item" v-show="taskMd5">
              <Button class="search-btn"
                type="primary"
                @click="getData">刷新</Button>
            </Col>
            <Col class="search-item" style="text-align:right;width:380px;font-size:14px;">
              <div style="padding-top:10px;">文件下载成功后，系统保存30天，请在30天内保存下载数据</div>
            </Col>
          </Row>
        </Row>
      </div>
      <Table stripe
        :loading="isloading"
        class="table-list"
        id="drawerTable"
        :max-height="drawTableHeight"
        :columns="drawerColumns"
        :data="drawerData">
        <template slot-scope="{ row }" slot="downLoadStatus">
          {{ getEnumsName(row.downLoadStatus, statusList) }}
        </template>
        <template slot-scope="{ row }" slot="action">
          <a :href="row.filePath">
            <i class="iconsys iconbaocundaobendi" title="保存到本地"  v-if="row.downLoadStatus == '2'">
            </i>
          </a>
          <Poptip confirm title="你确定要删除吗？" transfer @on-ok="sureDel(row)" style="text-align:left">
            <i class="iconsys icondel" title="删除" v-if="row.downLoadStatus == '2' || row.downLoadStatus == '3'"></i>
          </Poptip>
        </template>
      </Table>
      <Row type="flex">
        <Col span="24">
          <div class="page-box">
            <Page :total="total"
              :page-size="pageSize"
              :current="pageIndex"
              :page-size-opts="$pageSizeOpts"
              show-total
              show-sizer
              @on-change="changePageIndex"
              @on-page-size-change="changePageSize" />
          </div>
        </Col>
      </Row>
    </Drawer>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { getTaskList, delTask, addTask, getTaskModule } from '@/api/tools'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'DownCenter',
  components: { vueTreeselectChoice },
  data () {
    return {
      taskModuleList: [],
      isloading: false,
      statusList: [
        { value: '0', label: '已提交' },
        { value: '1', label: '正在下载' },
        { value: '2', label: '下载成功' },
        { value: '3', label: '下载失败' }
      ],
      drawerData: [],
      drawerColumns: [
        {
          title: '任务时间',
          key: 'createTime'
        },
        {
          title: '任务模块',
          key: 'taskModuleName'
        },
        {
          title: '任务名称',
          key: 'fileName',
          width: 250
        },
        {
          title: '下载状态',
          slot: 'downLoadStatus'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ],
      visible: false,
      shopValue: [],
      searchObj: {
        shopId: [],
        downLoadStatus: '2',
        taskModule: -1
      },
      drawTableHeight: 200,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      taskMd5: '',
      treeselectoptions: []
    }
  },
  props: {
    perms: {
      type: String,
      default: ''
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId
    })
  },
  watch: {
    visible (val) {
      if (val) {
        if (this.taskMd5) {
          setTimeout(() => {
            this.getData()
          }, 100)
        } else {
          this.searchObj.downLoadStatus = '2'
          this.searchObj.taskModule = -1
          this.searchObj.shopId = []
          this.pageSize = 10
          this.search()
        }
      } else {
        this.taskMd5 = ''
      }
    }
  },
  mounted () {
    this.getTaskModule()
    this.calcDrawTableHeight()
    window.addEventListener('resize', this.calcDrawTableHeight)
  },
  methods: {
    getTaskModule () {
      getTaskModule({}).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.taskModuleList = result.data
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getEnumsName (value, enums) {
      const result = enums.filter(item => item.value === ('' + value))
      return result[0] ? result[0].label : ''
    },
    deepTraversal (data) {
      const result = []
      data.forEach(item => {
        const loop = data => {
          result.push(data.id)
          let child = data.childList
          if (child.length) {
            for (let i = 0; i < child.length; i++) {
              loop(child[i])
            }
          }
        }
        loop(item)
      })
      return result
    },
    async handleShop () {
      // const ids = await this.$refs.vueTreeselectChoice.getShopId()
      // this.searchObj.shopId = ids
      this.search()
    },
    addTask (params) {
      addTask({
        merchantId: this.merchantId,
        operator: this.userId,
        ...params
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.taskMd5 = result.data.taskMd5
          if (result.data.isDownLoad) {
            this.$Modal.success({
              title: '数据已加入下载列表! 请点击下载中心查看',
              closable: true,
              onOk: () => {
                this.visible = true
              },
              onCancel: () => {
                this.taskMd5 = ''
              }
            })
          } else {
            this.$Modal.warning({
              title: '数据已下载到任务列表! 请前往任务列表保存到本地',
              closable: true,
              okText: '前往下载中心',
              onOk: () => {
                this.visible = true
              },
              onCancel: () => {
                this.taskMd5 = ''
              }
            })
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    // 关闭
    handleClose () {
      // debugger
      this.shopValue = []
      // this.searchObj.shopId = []
    },
    async getData () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      let params = {}
      if (this.taskMd5) {
        params.taskMd5 = this.taskMd5
      } else {
        if (!this.searchObj.downLoadStatus && this.searchObj.downLoadStatus !== '0') {
          this.$Message.error('请选择文件状态')
          return
        }
        if (this.shopValue.length > 0 && this.searchObj.shopId.length === 0) {
          // debugger
          this.$Message.error('请选择门店')
          return
        }
        params = {
          merchantId: this.merchantId,
          downLoadStatus: this.searchObj.downLoadStatus,
          taskModule: this.searchObj.taskModule === -1 ? '' : this.searchObj.taskModule,
          shopIds: this.searchObj.shopId,
          offset: (this.pageIndex - 1) * this.pageSize,
          limit: this.pageSize
        }
      }
      this.isloading = true
      getTaskList(params).then(res => {
        this.isloading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.drawerData = result.data || []
          this.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    calcDrawTableHeight () {
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight
      this.drawTableHeight = clientHeight - 280
    },
    sureDel (row) {
      delTask({
        merchantId: this.merchantId,
        id: row.id
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.calcDrawTableHeight)
  }
}
</script>
<style lang="less" scoped>
  .downbtn {
    position: fixed;
    z-index: 10;
    width: 56px;
    height: 56px;
    right: 0;
    top: 50%;
    margin-top: -28px;
    opacity: 0.9;
    background: #2D8CF0;
    box-shadow: 0 1px 6px 0 rgba(0,0,0,0.30);
    border-radius: 4px 0 0 4px;
    cursor: pointer;
    .downicon {
      width: 56px;
      text-align: center;
      padding-top: 5px;
        i {
          font-size: 16px;
          margin: 0;
          color: #fff;
        }
    }
    .downp {
      width: 56px;
      text-align: center;
      color: #fff;
      font-size: 12px;
    }
  }
  .search-box .search-item {
    margin-left: 10px;
    padding-top: 10px;
  }
</style>
<style>
  #drawerTable.ivu-table-wrapper {
    overflow: hidden !important;
  }
  .ivu-modal-confirm-head-title {
    margin-left: 5px;
    font-size: 14px;
    color: #464C5B;
    font-weight: normal;
  }
</style>
